#!/usr/bin/env Python
# coding=utf-8
from .logHelper import logger
from .Fields import Field
from .PooledBQuery import queryHelper
from flask import current_app

class ModelMetaclass(type):
    def __new__(cls, name, bases, attrs):
        if name == 'Model':
            return type.__new__(cls, name, bases, attrs)
        tableName = attrs.get('__table__', None) or name
        # logging.info('found model: %s (table: %s)' % (name, tableName))
        mappings = dict()
        fields = []
        primaryKey = None
        for k, v in attrs.items():
            if isinstance(v, Field):
                # logging.info('  found mapping: %s ==> %s' % (k, v))
                mappings[k] = v
                if v.primary_key:
                    # 找到主键:
                    # if primaryKey:
                    # raise StandardError('Duplicate primary key for field: %s' % k)
                    primaryKey = k
                else:
                    fields.append(k)
        # if not primaryKey:
        # raise StandardError('Primary key not found.')
        for k in mappings.keys():
            attrs.pop(k)
        escaped_fields = list(map(lambda f: '%s' % f, fields))
        attrs['__mappings__'] = mappings  # 保存属性和列的映射关系
        attrs['__table__'] = tableName
        attrs['__primary_key__'] = primaryKey  # 主键属性名
        attrs['__fields__'] = fields  # 除主键外的属性名
        # attrs['__select__'] = 'select %s, %s from %s '% (primaryKey, ', '.join(escaped_fields), tableName)
        # attrs['__insert__'] = 'insert into `%s` (%s, `%s`) values (%s)' % (tableName, ', '.join(escaped_fields), primaryKey, create_args_string(len(escaped_fields) + 1))
        # attrs['__update__'] = 'update %s set %s where `%s`=?' % (tableName, ', '.join(map(lambda f: '`%s`=?' % (mappings.get(f).name or f), fields)), primaryKey)
        # attrs['__delete__'] = 'delete from %s where `%s`=?' % (tableName, primaryKey)
        return type.__new__(cls, name, bases, attrs)


class Model(dict, metaclass=ModelMetaclass):
    def __init__(self, **kw):
        super(Model, self).__init__(**kw)

    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError:
            raise AttributeError(r"'Model' object has no attribute '%s'" % key)

    def __setattr__(self, key, value):
        self[key] = value

    def getValue(self, key):
        return getattr(self, key, None)

    def getValueOrDefault(self, key):
        value = getattr(self, key, None)
        if value is None:
            field = self.__mappings__[key]
            # print("field -> %s" % field)
        # print("v:%s"%value)

    @classmethod
    def Getlist(cls, where=None, args=None):
        sql = "select %s, %s from %s" % (cls.__primary_key__, ','.join(cls.__fields__), cls.__table__)
        if where:
            sql = "%s %s" % (sql, where)
        #rs = queryHelper.select(sql, args, True)
        #rs = queryHelper().select(sql, args, True)
        with queryHelper() as query:
            rs = query.fetch(sql=sql,params=None,size=1)
            #return rs
            if rs is None:
                return None
            return [cls(**r) for r in rs]

    @classmethod
    def GetInfo(cls,where=None,args=None):
        ' find object by primary key. '
        sql = "select %s, %s from %s" %  (cls.__primary_key__ , ','.join(cls.__fields__),cls.__table__)
        if where:
            sql = "%s where %s" % (sql,where)
        with queryHelper() as query:
            rs = query.fetch(sql,args,None)
            logger.info(sql)
            if len(rs)==0 :
                return None
            return cls(**rs[0])

    @classmethod
    def SpPage(cls, pagesize=1,pagecurrent=10, fields=None, where=None, order=None):
        if not fields:
            fields =  '%s,%s' %(cls.__primary_key__,( ','.join(cls.__fields__)))
        if not where:
            where = ''
        if not order:
            order= '%a desc' % cls.__primary_key__
        with queryHelper() as query:
            result,totalcount,pagecount = query.callproc_sp_page(
                fields,
                cls.__table__,
                where,
                order,
                pagesize,
                pagecurrent,
                '@totalcount',
                '@pagecount'
            )
            result = [cls(**r) for r in result]
            return result,totalcount,pagecount

    @classmethod
    def Save(self):
        args = list(map(self.getValue, self.__fields__))
        sql = "INSERT INTO %s(%s) VALUES (%s) ;SELECT LAST_INSERT_ID();" % (self.__table__ , ','.join(self.__fields__) , ','.join(list(map(lambda x : ("\'%s\'" % x),args))) )
        with queryHelper() as query:
            rows = query.execute(sql)
            logger.info(sql)
            if rows != 1:
                logger.warn('failed to insert record: affected rows: %s' % rows)
            #rs = DbConnection().Execute(sql)
            return sql